package com.youdianstar.app.common.widget.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.RecyclerView
import com.youdianstar.app.common.R


/**
 * File: FooterAdapter
 * Author: 82149 Create: 2021/9/22 18:56
 * Changes (from 2021/9/22)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class FooterAdapter(private val retry: () -> Unit) : LoadStateAdapter<FooterAdapter.FooterHolder>() {
    class FooterHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val pbLoading by lazy {
            itemView.findViewById<ProgressBar>(R.id.progress_bar)
        }
        val tvRetry by lazy {
            itemView.findViewById<TextView>(R.id.bt_retry)
        }

        fun onRetryClick(retry: () -> Unit){
            tvRetry.setOnClickListener {
                retry.invoke()
            }
        }
    }

    override fun onBindViewHolder(holder: FooterHolder, loadState: LoadState) {
        holder.pbLoading.isVisible = loadState is LoadState.Loading
        holder.tvRetry.isVisible = loadState is LoadState.Error
    }

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): FooterHolder {
        val layout = LayoutInflater.from(parent.context).inflate(R.layout.paging_footer_item, parent, false)
        val holder = FooterHolder(layout)
        holder.onRetryClick(retry)
        return holder
    }
}